<template>
  <div class="user-container">
    <el-form size="small" :inline="true">
      <el-form-item>
        <el-input
          v-model="username"
          clearable
          placeholder="请输入标题"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getList" type="primary"
          >查询</el-button
        >
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="userList" border style="width: 100%">
      <el-table-column prop="avatar" label="头像" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 80px; height: 50px"
            :src="scope.row.avatar"
            fit="cover"
            :preview-src-list="srcList"
            hide-on-click-modal="true"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="昵称" width="120" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column
        prop="status"
        width="120"
        label="账号状态"
        align="center"
      >
        <template slot-scope="scope">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :disabled="true"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template slot-scope="scope">
          {{ formatDate(1, scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间">
        <template slot-scope="scope">
          {{ formatDate(1, scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="address" align="center" label="操作" width="120">
        <template slot-scope="scope">
          <el-popconfirm
            @onConfirm="deleteClick(scope.row.id)"
            title="确定删除该用户吗？"
          >
            <template #reference>
              <el-button
                :disabled="userInfo.username !== 'admin'"
                style="color: red"
                type="text"
                size="small"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
          <el-button
            style="margin-left: 0.2rem"
            type="text"
            @click="editClick(scope.row)"
            :disabled="userInfo.username !== 'admin'"
            size="small"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- <div class="page">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div> -->

    <el-dialog :title="title" :visible.sync="dialogVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="账号状态：" prop="status">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="form.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :disabled="userInfo.username !== 'admin'"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="昵称：" prop="nickname">
          <el-input v-model="form.nickname"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>

        <el-form-item label="头像：" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9999/upload"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="onSuccess"
            name="file"
          >
            <img v-if="form.avatar" :src="form.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="btnLoading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, del, update } from "@/api/user";
import { mapGetters } from "vuex";
import { Message } from "element-ui";
export default {
  data() {
    return {
      // page: 1,
      // pageSize: 10,
      // total: 0,

      dialogVisible: false,
      title: "",
      username: "",
      srcList: [],
      userList: [],

      form: {
        id: "",
        nickname: "",
        email: "",
        avatar: "",
        status: 1,
      },

      btnLoading: false,
      loading: false,

      rules: {
        nickname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
        ],
        email: [{ required: true, message: "请输入用户邮箱", trigger: "blur" }],
        avatar: [
          { required: true, message: "请上传用户头像", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  mounted() {
    this.getList();
  },
  methods: {
    async submit() {
      this.btnLoading = true;
      const res = await update(this.form);
      this.btnLoading = false;
      if (res.code === 200) {
        Message.success(res.message);
        this.getList();
        this.dialogVisible = false;
      }
    },
    // 上传文件之前
    beforeUpload(file) {
      const max_size = file.size / 1024 / 1024 < 2;
      if (!max_size) {
        this.$message.error("上传图片不能超过2MB");
        return false;
      }
      this.btnLoading = true;
      return true;
    },
    // 文件上传成功
    onSuccess(response) {
      if (response.code === 200) {
        Message.success(response.message);
        this.form.avatar = response.data;
        this.btnLoading = false;
      }
    },
    // 编辑用户信息
    editClick(row) {
      if (row.id == this.userInfo.id) {
        this.$message.error("不能修改自己的账号信息");
        return;
      }
      this.title = row.username;
      // 遍历 row 只给form中存在的键赋值
      for (const key in row) {
        if (this.form.hasOwnProperty(key)) {
          this.form[key] = row[key];
        }
      }
      this.dialogVisible = true;
    },
    // 删除用户信息
    async deleteClick(id) {
      if (id == this.userInfo.id) {
        this.$message.error("不能删除管理员账号");
        return;
      }
      const res = await del(id);
      if (res.code === 200) {
        this.$message.success(res.message);
        this.getList();
      }
    },

    // 改变分页
    // handleCurrentChange(payload) {
    //   this.page = payload;
    //   this.getList();
    // },

    // 查询用户信息
    async getList() {
      this.srcList = [];
      const params = {
        // page: this.page,
        // pageSize: this.pageSize,
        username: this.username,
      };
      this.loading = true;
      const res = await list(params);
      this.userList = res.data;
      res.data.forEach((element) => {
        this.srcList.push(element.avatar);
      });
      // this.total = res.data.total;
      this.loading = false;
    },
  },
};
</script>

<style lang="scss" scoped>
// .page {
//   margin-top: 15px;
//   display: flex;
//   justify-content: center;
// }

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 160px;
  height: 160px;
  &:hover {
    border-color: #409eff;
  }
  .avatar {
    width: 160px;
    height: 160px;
    display: block;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 160px;
    height: 160px;
    line-height: 160px;
    text-align: center;
  }
}
</style>
